import json
import sys
from django.core.management.base import BaseCommand
from django_redis import get_redis_connection
from overview.consumers import UserActivityConsumer, broadcast_user_activity
from mongolog.serializers import UserActivityLogSerializer


class Command(BaseCommand):
    help = 'Subscribe real-time user activities from redis message queue'

    def add_arguments(self, parser):
        pass

    def handle(self, *args, **options):
        redis = get_redis_connection('default')

        pubsub = redis.pubsub()
        pubsub.subscribe(UserActivityConsumer.groups[0])
        print(f"Subscribed channel '{UserActivityConsumer.groups[0]}' through {pubsub.connection}")

        for item in pubsub.listen():
            if item['type'] == 'message':
                try:
                    message = json.loads(item['data'])
                    serializer = UserActivityLogSerializer(data=message)
                    if serializer.is_valid():
                        broadcast_user_activity(serializer.data)
                    print(message)
                except Exception as e:
                    print('Broadcast user activity failed, %s' % e, file=sys.stderr)
